<?php

namespace app\common\model;

use addons\xykeep\exception\Exception;
use app\api\model\xykeep\User;
use app\common\model\Coupons as CouponsModel;
use think\Model;


class CouponsOrder extends Model
{

    

    

    // 表名
    protected $name = 'coupons_order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_type_text',
        'paytime_text',
        'platform_text',
        'status_text'
    ];
    

    
    public function getPayTypeList()
    {
        return ['wechat' => __('Wechat'), 'balance' => __('Balance')];
    }

    public function getPlatformList()
    {
        return ['wxMiniProgram' => __('Platform wxminiprogram'), 'wxOfficialAccount' => __('Platform wxofficialaccount')];
    }

    public function getStatusList()
    {
        return ['-3' => __('Status -3') ,'-1' => __('Status -1'), '0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPlatformTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['platform']) ? $data['platform'] : '');
        $list = $this->getPlatformList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    /**
     * 添加订单
     */
    public static function addOrder($params){

        extract($params);


        $price = CouponsModel::where([
            'id' => 1
        ])->value('price');
        if (!$price) {
            new Exception('信息券不存在！');
        }
        $price = (String)$price;

        $total_money = bcmul($price, (String)$buy_num,2);

        if($total_money <= 0){
            new Exception('请选择信息券');
        }

        $user = User::info();

//        if($user->id == 15){
//            $total_money = 0.01;
//        }

        $close_time = 15;//15分钟为支付自动关闭
        $orderData = [];
        $orderData['order_sn'] = createOrderNo();
        $orderData['user_id'] = $user->id;
        $orderData['total_amount'] = $total_money;
        $orderData['total_fee'] = $total_money;
        $orderData['ext'] = json_encode([
            'expired_time' => time() + ($close_time * 60),
        ]);
        $orderData['buy_num'] = $buy_num;

        $order = self::create($orderData);

        //订单关闭队列
        //Queue::later(($close_time * 60), '\addons\xykeep\job\Order@autoClose', ['order' => $order,'type'=>'vip'], 'XYkeep');


        return $order;
    }


    /*
     * 订单支付成功
     * */
    public function paySuccess($order, $notify)
    {
        $order->status = 1;
        $order->paytime = time();
        $order->transaction_id = $notify['transaction_id'];
        $order->payment_json = $notify['payment_json'];
        $order->pay_type = $notify['pay_type'];
        $order->pay_fee = $notify['pay_fee'];
        $order->save();

        $_time = time();

        $CouponsModel = new CouponsModel();
        $UserCouponsLog = new UserCouponsLog();

        //插入日志
        $couponsInfo = $CouponsModel->where(['id' => 1])->find();
        $UserCouponsLog->save([
            'nums' => $order['buy_num'],
            'price' => $couponsInfo['price'],
            'user_id' => $order->user_id,
            'type' => 'buy',
            'order_sn' => $order->order_sn,
        ]);

        $UserCouponsModel = new UserCoupons();

        //实际发放信息券，如果以前有就往上增加数量，反之则新建
        $alreadyCoupons = $UserCouponsModel->where([
            'user_id' => $order->user_id,
        ])->find();
        if($alreadyCoupons){
            $UserCouponsModel->where([
                'id' => $alreadyCoupons['id'],
            ])->update([
                'nums' => $order['buy_num'] + $alreadyCoupons['nums'],
                'buyed' => $order['buy_num'] + $alreadyCoupons['buyed'],
                'updatetime' => $_time
            ]);
        }else{
            $UserCouponsModel->insert([
                'buyed' => $order['buy_num'],
                'nums' => $order['buy_num'],
                'price' => $couponsInfo['price'],
                'orginal_price' => $couponsInfo['orginal_price'],
                'user_id' => $order->user_id,
                'createtime' => $_time,
            ]);
        }

        // 支付后监听
        $params = ['order'=>$order,'type'=>'coupons'];
        \think\Hook::listen('xykeep_order_payed_after', $params);

    }
}
